package com.jacky.iot.resources;

import org.eclipse.californium.core.CoapResource;
import org.eclipse.californium.core.coap.Request;
import org.eclipse.californium.core.server.resources.CoapExchange;
import org.eclipse.californium.elements.UDPConnector;
import org.eclipse.californium.elements.UdpMulticastConnector;
import org.eclipse.californium.elements.util.StringUtil;

import java.util.Random;

public class MulticastHelloResource extends CoapResource {

    private int id;

    public MulticastHelloResource() {
        super("multicast-hello");
        getAttributes().setTitle("Hello-World resource");
        id = new Random(System.currentTimeMillis()).nextInt(100);
        System.out.println("coap server: " + id);
    }


    @Override
    public void handleGET(CoapExchange exchange) {
        if (exchange.isMulticastRequest()) {
            Request request = exchange.advanced().getRequest();
            exchange.respond("Hello Multicast-World " + id + "\nReceived via " + StringUtil.toDisplayString(request.getLocalAddress()));
        } else {
            exchange.respond("Hello UniCast-World " + id);
        }
    }
}
